package com.elong.android.specialhouse.utils;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * {@link #getInstance(Context)}此种方式可能会造成内存泄露问题。<br/>
 * 修改为{@link #init(Application)}方式初始化进来一个{@link Context}。
 *
 * @update lizheng 2015-09-25
 */
public class ToastUtils {
    // private static Context mContext;
    private static Toast mToast = null;

    private static Application mApp;

    public static void init(Application application) {
        mApp = application;
    }

    @SuppressLint("ShowToast")
    private static Toast getInstance(Context context) {
        if (mToast != null)
            return mToast;
        synchronized (Toast.class) {
            if (mToast == null) {
                mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
            }
        }
        return mToast;
    }

    @SuppressLint("ShowToast")
    private static Toast getInstance() {

        if (null == mApp) {
            throw new IllegalArgumentException("context为空。没有在Application中进行初始化");
        }

        if (mToast != null)
            return mToast;
        synchronized (Toast.class) {
            if (mToast == null) {
                mToast = Toast.makeText(mApp, "", Toast.LENGTH_SHORT);
            }
        }
        return mToast;
    }

    // public static void showToast(Context context) {
    // showToast(context, null);
    // }

    public static void show(Context context, int resId) {
        show(context, mApp.getString(resId), Toast.LENGTH_SHORT);
    }

    public static void show(Context context, int resId, int duration) {
        show(context, mApp.getString(resId), duration);
    }

    public static void show(Context context, String text) {
        show(context, text, Toast.LENGTH_SHORT);
    }

    public static void show(Context context, String text, int duration) {
        // mToast = getInstance(context);
        mToast = getInstance();
        mToast.setText(text);
        mToast.setDuration(duration);
        mToast.show();
    }

    public static void show(String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        show(null, text, Toast.LENGTH_SHORT);
    }

    public static void show(int strResId) {
        show(null, mApp.getString(strResId), Toast.LENGTH_SHORT);
    }

    public static void dismiss() {
        if (mToast != null) {
            mToast.cancel();
            mToast = null;
        }
    }
}
